// pageB/pages/wallet/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        activeTab: 0, // 0-接单记录 1-提现记录
        pages: 1,
        size: 20,
        noMore: false,
        availAcount: 0,
        orderList: [
        {
            acceptTime: "0001-01-01T00:00:00",
addTime: "2025-07-01T13:36:41.780768",
adminRemark: null,
auntPhone: "13813357897",
caregiverId: 636,
caregiverNickname: "肖婷婷",
checkinPhoto: "https://xssp.xjdio.com/images/Xjd/image/20250705/202556050407437cd7769b-c757-4586-b968-c66f973f6c07.png",
checkinTime: "0001-01-01T00:00:00",
city: "闵行区",
clientName: "文君",
clientPhone: "13813357897",
comment: "更多的对方过后就，非常感谢。",
detailAddress: "图书城公寓文创楼2号",
dispatcherId: 636,
dispatcherNickname: "",
district: "",
flag: false,
id: 11,
lastUpdateTime: "2025-09-22T00:08:55.422872",
latitude: 31.114041,
longitude: 121.373637,
notes: "索拉卡回家考虑",
price: 888,
province: "上海市",
raterAvatarUrl: "https://xssp.xjdio.com/images/Xjd/chatHead/1/20250029100638f1a2eaf2-83db-47a2-a7c9-bb844d3fd279.png",
raterName: "肖婷婷",
rateraccountId: 636,
rating: 5,
ratingTime: "2025-07-07T13:58:54.817292",
remark: null,
serviceContent: "奶皮子酸奶",
serviceDate: "2025-10-01T00:00:00",
serviceTime: "2025-07-01T03:00:00",
serviceType: "深度保洁",
status: "completed",
statusText: "已完成",
tenantId: 0,
        }
            // {
            //     id: 1,
            //     serviceContent: '日常保洁',
            //     price: 150.00,
            //     serviceTime: '2023-07-15 14:00-16:00',
            //     address: '北京市朝阳区XX小区1号楼101',
            //     customerName: '张先生',
            //     customerPhone: '138****1234',
            //     remark: '需要带宠物',
            //     status: '待评价',
            //     // 评价数据
            //     rating: 0,
            //     comment: "阿姨服务非常专业，厨房清洁特别到位，比预期效果还要好。沟通顺畅，提前到达，工作认真负责，客户非常满意。",
            //     ratingTime: '2023-08-15 15:20:10'
            // },
            // {
            //     id: 2,
            //     serviceContent: '深度清洁',
            //     price: 280.00,
            //     serviceTime: '2023-07-18 09:00-12:00',
            //     address: '北京市海淀区XX花园3号楼202',
            //     customerName: '李女士',
            //     customerPhone: '139****5678',
            //     remark: '厨房油污较重',
            //     status: '待评价',
            //     // 评价数据
            //     rating: 5,
            //     comment: "阿姨服务非常专业，厨房清洁特别到位，比预期效果还要好。沟通顺畅，提前到达，工作认真负责，客户非常满意。",
            //     ratingTime: '2023-08-15 15:20:10'
            // },
            // {
            //     id: 3,
            //     serviceContent: '家电清洗',
            //     price: 120.00,
            //     serviceTime: '2023-07-20 13:00-15:00',
            //     address: '北京市西城区XX胡同15号院',
            //     customerName: '王先生',
            //     customerPhone: '137****9012',
            //     remark: '清洗空调和抽油烟机',
            //     status: '已完成',
            //     // 评价数据
            //     rating: 5,
            //     comment: "阿姨服务非常专业，厨房清洁特别到位，比预期效果还要好。沟通顺畅，提前到达，工作认真负责，客户非常满意。",
            //     ratingTime: '2023-08-15 15:20:10'
            // },
            // {
            //     id: 4,
            //     serviceContent: '新居开荒',
            //     price: 450.00,
            //     serviceTime: '2023-07-22 08:00-17:00',
            //     address: '北京市丰台区XX新苑8号楼302',
            //     customerName: '赵女士',
            //     customerPhone: '135****3456',
            //     remark: '新房装修后首次清洁',
            //     status: '待评价',
            //     // 评价数据
            //     rating: 5,
            //     comment: "阿姨服务非常专业，厨房清洁特别到位，比预期效果还要好。沟通顺畅，提前到达，工作认真负责，客户非常满意。",
            //     ratingTime: '2023-08-15 15:20:10'
            // },
            // {
            //     id: 5,
            //     serviceContent: '玻璃清洁',
            //     price: 180.00,
            //     serviceTime: '2023-07-25 10:00-12:00',
            //     address: '北京市东城区XX大厦B座1502',
            //     customerName: '陈先生',
            //     customerPhone: '136****7890',
            //     remark: '高层外窗清洁',
            //     status: '已完成',
            //     // 评价数据
            //     rating: 5,
            //     comment: "阿姨服务非常专业，厨房清洁特别到位，比预期效果还要好。沟通顺畅，提前到达，工作认真负责，客户非常满意。",
            //     ratingTime: '2023-08-15 15:20:10'
            // }
        ],
        withdrawalList: [
            // {
            //     id: 1,
            //     amount: 1000.00,
            //     applyTime: '2023-07-25 14:30',
            //     name: '张阿姨',
            //     phone: '138****8888',
            //     method: '支付宝',
            //     account: 'zhang***@example.com'
            // },
            // {
            //     id: 2,
            //     amount: 800.00,
            //     applyTime: '2023-07-18 09:15',
            //     name: '张阿姨',
            //     phone: '138****8888',
            //     method: '微信支付',
            //     account: 'wxid_zhang***'
            // },
            // {
            //     id: 3,
            //     amount: 500.00,
            //     applyTime: '2023-07-10 16:45',
            //     name: '张阿姨',
            //     phone: '138****8888',
            //     method: '银行转账',
            //     account: '中国银行 **** **** 5678'
            // },
            // {
            //     id: 4,
            //     amount: 1200.00,
            //     applyTime: '2023-06-28 11:20',
            //     name: '张阿姨',
            //     phone: '138****8888',
            //     method: '支付宝',
            //     account: 'zhang***@example.com'
            // }
        ],
        withdrawAmount: '',
    },
    GetmyServiceOrders(param1, param2) {
        return wx.Http.post("/ServiceOrderAPPService/GetmyServiceOrders", {
            PageIndex: param1,
            PageCount: param2

        });
    },
    GetWithdrawalRecordlist(param1, param2) {
        return wx.Http.post("/WithdrawalRecordAppService/GetWithdrawalRecordlist", {
            PageIndex: param1,
            PageCount: param2

        });
    },
    CreateWithdrawalRecord(param) {
        return wx.Http.post("/WithdrawalRecordAppService/CreateWithdrawalRecord", {
            Amount: param.amount,
            Status: param.status,
            CaregiverNickname: param.caregiverNickname,
            AuntPhone: param.auntPhone,
            Notes: ''

        });
    },
    // 评价文本映射
    ratingTexts: ["非常差", "比较差", "一般", "比较好", "非常好"],

    // 提现按钮点击事件
    onWithdraw() {
        wx.showToast({
            title: '提现功能开发中',
            icon: 'none'
        })
    },
    onWithdrawInput: function (e) {
        this.setData({
            withdrawAmount: e.detail.value
        });
    },
    openWithdrawModal: function () {
        this.setData({
            showWithdrawModal: true,
            formattedBalance: this.data.availAcount
        });
    },
    closeWithdrawModal: function () {
        this.setData({
            showWithdrawModal: false,
            withdrawAmount: ''
        });
    },
    confirmWithdraw: function () {
        const _this = this;
        // 校验输入
        const amount = parseFloat(this.data.withdrawAmount);
        if (isNaN(amount)) {
            wx.showToast({
                title: '请输入有效金额',
                icon: 'none'
            });
            return;
        }
        if (amount <= 0) {
            wx.showToast({
                title: '提现金额需大于0',
                icon: 'none'
            });
            return;
        }
        if (amount > this.data.formattedBalance) {
            wx.showToast({
                title: '提现金额超过余额',
                icon: 'none'
            });
            return;
        }
        // 更新余额
        const newBalance = this.data.formattedBalance - amount;
        const formattedBalance = this.formatBalance(newBalance);
        // 生成提现记录
        // const newWithdrawal = {
        //     id: this.data.withdrawalList.length + 1,
        //     amount: amount,
        //     applyTime: this.getCurrentTime(),
        //     name: '张阿姨',
        //     phone: '138****8888',
        //     method: '微信零钱',
        //     account: '微信账户'
        // };
        let param = {
            amount,
            status: '申请中',
            caregiverNickname: wx.getStorageSync('Monkey').nickname,
            auntPhone: wx.getStorageSync('Monkey').userPhone
        }
        this.CreateWithdrawalRecord(param).then((res) => {
            console.log(res.data)
            if (res.data) {
                _this.GetWithdrawalRecordlist(1, 20).then((res) => {
                    console.log(res.data)
                    if (res.data) {
                        this.setData({
                            availAcount: newBalance,
                            formattedBalance: formattedBalance,
                            // withdrawalList: [newWithdrawal, ...this.data.withdrawalList], // 新的记录放在最前面
                            showWithdrawModal: false,
                            withdrawAmount: '',
                            activeTab: 1,
                            withdrawalList: res.data.length > 0 ? res.data : this.data.withdrawalList
                        })
                        wx.Http.post("/AccountAppService/GetUserinfo", {}).then((res) => {
                            if (res.data?.value) {
                                wx.setStorageSync("Monkey", res.data.value);
                                _this.setData({
                                    availAcount:res.data.value.availAcount
                                })
                            }
                        });
                        wx.showToast({
                            title: '提现申请成功',
                            icon: 'success'
                        });
                    }

                })
            }
        })

       

    },
    formatBalance: function (balance) {
        // 将数字转为字符串，保留两位小数，并添加千位分隔符
        return balance.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    getCurrentTime: function () {
        const date = new Date();
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 选项卡切换
    switchTab(e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            activeTab: index,
            noMore: false
        });
        if (this.data.activeTab == 0) {
            this.GetmyServiceOrders(1, 20).then((res) => {
                console.log(res.data)
                this.setData({
                    orderList: res.data.list,
                    noMore: res.data.list.length < this.data.size
                })
            })
        } else {
            this.GetWithdrawalRecordlist(this.data.pages, this.data.size).then((res) => {
                console.log(res.data)
                if (res.data) {
                    this.setData({
                        withdrawalList: res.data.length > 0 ? res.data : this.data.withdrawalList
                    })
                }

            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (wx.getStorageSync('Monkey')) {
            var { availAcount } = wx.getStorageSync('Monkey')
            this.GetmyServiceOrders(1, 20).then((res) => {
                console.log(res.data)
                this.setData({
                    availAcount,
                    orderList: res.data.list,
                    noMore: res.data.list.length < this.data.size
                })
            })

        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    // 下拉刷新
    //  onRefresh() {
    //     this.setData({
    //         page: 1,
    //         orders: [],
    //         noMore: false
    //     }, () => {
    //         this.loadOrders(this.data.filterType);
    //         wx.stopPullDownRefresh();
    //     });
    // },

    // // 上拉加载更多
    // onReachBottom() {
    //     if (!this.data.noMore) {
    //         this.setData({ page: this.data.page + 1 }, () => {
    //             this.loadOrders(this.data.filterType);
    //         });
    //     }
    // },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        const _this = this;
        this.setData({
            pages: 1,
            orders: [],
            noMore: false
        }, () => {
            if (wx.getStorageSync('Monkey')) {
                var { availAcount } = wx.getStorageSync('Monkey')
                if (_this.data.activeTab == 0) {
                    _this.GetmyServiceOrders(1, 20).then((res) => {
                        console.log(res.data)
                        _this.setData({
                            availAcount,
                            orderList: res.data.list,
                            noMore: res.data.list.length < _this.data.size
                        })
                    })
                } else {
                    _this.GetWithdrawalRecordlist(_this.data.pages, _this.data.size).then((res) => {
                        console.log(res.data)
                        if (res.data) {
                            _this.setData({
                                withdrawalList: res.data.length > 0 ? res.data : _this.data.withdrawalList
                            })
                        }

                    })
                }


            }
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        const _this = this;
        if (!this.data.noMore) {
            this.setData({ page: _this.data.pages + 1 }, () => {

                if (_this.data.activeTab == 0) {
                    _this.GetmyServiceOrders(1, 20).then((res) => {
                        console.log(res.data)
                        _this.setData({
                            availAcount,
                            orderList: res.data.list,
                            noMore: res.data.list.length < _this.data.size
                        })
                    })
                } else {
                    _this.GetWithdrawalRecordlist(_this.data.pages, _this.data.size).then((res) => {
                        console.log(res.data)
                        if (res.data) {
                            _this.setData({
                                withdrawalList: res.data.length > 0 ? res.data : _this.data.withdrawalList
                            })
                        }

                    })
                }
            });
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})